#!/usr/bin/env python
#-*- coding:utf8 -*-
import web
from app.controllers.application_controller import ApplicationController
from app.helpers.account_helper import Helper
from app.models.user import User
class AccountController(ApplicationController):
    User = User()
    def initialize(self):
        super(AccountController,self).initialize()
    #会员登陆
    def sign_in(self):
        if self.login:
            raise web.seeother('/')
        if self.method == 'POST':
            post = Helper.post()
            if Helper.validation(r".*@.*", post['email']) is False:
                return self.render_json({'msg':'邮箱格式不正确.'})
            if Helper.validation(r".{6,15}$", post['key']) is False:
                return self.render_json({'msg':'密码格式不正确.'})
            password = Helper.hash(post['key'])
            user = self.User.get_by("(email = '%s' and password = '%s') and status = 1" % (post['email'],password))
            if user is None:
                return self.render_json({'msg':'帐号\密码错误.'})
            else:
                web.ctx.session.login   = True
                web.ctx.session.mid     = user.id
                web.ctx.session.account = user.account
                web.ctx.session.email   = user.email
                web.ctx.session.is_admin= user.is_admin
                web.ctx.session.user    = user
                return self.render_json({'status':True})
    #会员注册
    def sign_up(self):
        if self.login:
            raise web.seeother('/')
        if self.method == 'POST':
            post = Helper.post()
            if Helper.validation(r".([a-z0-9]+){4,12}", post['account']) is False:
                return self.render_json({'msg':'账号格式不正确.'})
            if Helper.validation(r".*@.*", post['email']) is False:
                return self.render_json({'msg':'邮箱格式不正确.'})
            if Helper.validation(r".{6,15}$", post['key']) is False:
                return self.render_json({'msg':'密码格式不正确.'})
            post['password'] = Helper.hash(post['key'])
            if self.User.create(post):
                return self.render_json({'status': True })
            else:
                return self.render_json({'msg':'注册失败.'})
    #退出登陆
    def sign_out(self):
        self.load = False
        web.ctx.session.kill()
        raise web.seeother('/')
